package com.lty;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 邮件推送工具
 * @author lty
 */
@Component
@Slf4j
public class EmailUtil {

    @Resource
    private EmailSettingConfig emailSettingConfig;

    @Resource
    private TemplateEngine templateEngine;


    /**
     * 发送邮件
     * @param sendTo       接收者邮箱
     * @param title        邮件标题
     * @param templateName 邮件模板
     * @param o            模板替换对象
     */
    public void sendTemplateEmail(String sendTo, String title, String templateName, Object o) {

        EmailSetting es = emailSettingConfig.getEmailSetting();

        JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();

        // 设定邮箱服务器配置
        senderImpl.setHost(es.getHost());
        senderImpl.setUsername(es.getUsername());
        senderImpl.setPassword(es.getPassword());
        Properties prop = new Properties();

        // 服务器进行认证
        prop.put("mail.smtp.auth", "true");
        prop.put("mail.smtp.timeout", "20000");
        // 邮箱发送服务器端口,这里设置为465端口
        prop.setProperty("mail.smtp.port", "465");
        prop.setProperty("mail.smtp.socketFactory.port", "465");
        prop.put("mail.smtp.ssl.enable", "true");
        senderImpl.setJavaMailProperties(prop);

        // 发送html邮件
        MimeMessage mailMessage = senderImpl.createMimeMessage();
        MimeMessageHelper messageHelper = null;
        // 设置邮件内容
        try {
            messageHelper = new MimeMessageHelper(mailMessage, true, "utf-8");

            messageHelper.setTo(sendTo);
            messageHelper.setFrom(es.getUsername());
            messageHelper.setSubject(title);
            Context context = new Context();

            // 设置内容
            context.setVariables(beanToMap(o));

            // 获取模板html代码
            String content = templateEngine.process(templateName, context);
            // true表示HTML格式的邮件
            messageHelper.setText(content, true);
            // 发送邮件
            senderImpl.send(mailMessage);
        } catch (Exception e) {
            log.error(e.toString());
        }
    }

    /**
     * 将对象装换为map
     * @param bean
     * @return
     */
    public static <T> Map<String, Object> beanToMap(T bean) {
        Map<String, Object> map = new HashMap<>(16);
        if (bean != null) {
            BeanMap beanMap = BeanMap.create(bean);
            for (Object key : beanMap.keySet()) {
                map.put(String.valueOf(key), beanMap.get(key));
            }
        }
        return map;
    }
}
